﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace Skybot.Logs.Broken
{
    /// <summary>
    /// 转发出现故障时的日志处理类
    /// </summary>
    public class ForwardBrokegLog : ForwardWriteLog
    {
        /// <summary>
        /// 创建新的日志写入类
        /// </summary>
        /// <param name="basePath"></param>
        public ForwardBrokegLog(string basePath = "ForwardBrokegLog")
            : base(basePath)
        {

        }

        /// <summary>
        /// 找到写入的文件句柄
        /// </summary>
        /// <param name="dicName">目录名</param>
        /// <param name="toKen">为小时,分,秒,毫秒</param>
        /// <returns></returns>
        public StreamWriter FindStrear(string toKen, string dicName = "ForwardBrokegLog")
        {
            string key = dicName + toKen + "," + DateTime.Now.ToString("yyyy-MM-dd");
            WriteState cur = null;

            if (dic.TryGetValue(key, out cur))
            {
                return cur.FileStream;
            }
            return null;
        }


        /// <summary>
        /// 关闭文件句柄
        /// </summary>
        /// <param name="dicName">目录名</param>
        /// <param name="toKen">为小时,分,秒,毫秒</param>
        /// <returns></returns>
        public void CloseFile(string toKen, string dicName = "ForwardBrokegLog")
        {
            string key = dicName + toKen + "," + DateTime.Now.ToString("yyyy-MM-dd");
            WriteState cur = null;

            if (dic.TryGetValue(key, out cur))
            {
                //从队列中移除数据
                Delete(key);
            }

        }

        /// <summary>
        /// 手动删除文件
        /// </summary>
        /// <param name="dicName">目录名</param>
        /// <param name="toKen">为小时,分,秒,毫秒</param>
        /// <returns></returns>
        public bool DeleteFile(string toKen, string dicName = "ForwardBrokegLog")
        {
            string key = dicName + toKen + "," + DateTime.Now.ToString("yyyy-MM-dd");
            WriteState cur = null;

            if (dic.TryGetValue(key, out cur))
            {
                //从队列中移除数据
                Delete(key);
                if (System.IO.File.Exists(cur.Path))
                {
                    try
                    {
                        //删除文件
                        System.IO.File.Delete(cur.Path);
                        return true;
                    }
                    catch
                    {
                        return false;
                    }
                }

            }
            return false;

        }



        /// <summary>
        /// 写入发送文件
        /// </summary>
        /// <param name="dicName">目录名</param>
        /// <param name="toKen">标识:时,分,秒.毫秒</param>
        /// <param name="data"></param>
        public void Write(string toKen, string data, string dicName = "ForwardBrokegLog")
        {
            string key = dicName + toKen + "," + DateTime.Now.ToString("yyyy-MM-dd");
            //查找内存中已经存在的状态数据
            WriteState state = null;
            dic.TryGetValue(key, out state);
            if (state == null)
            {
                #region 首次添加

                lock (dic)
                {
                    state = new WriteState();
                    if (dic.TryAdd(key, state))
                    {
                        state.TerminalCode = dicName;
                        state.Key = key;
                        //创建Path
                        state.Path = LogPath(toKen);

                    }
                    else
                    {
                        var obj = dic[key];
                        if (obj != null)
                        {
                            state = obj;
                        }
                    }
                }
                try
                {
                    lock (dic)
                    {
                        state.FileStream = File.AppendText(state.Path);
                    }
                }
                catch
                {

                }

                #endregion

            }
            try
            {
                string writeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ;" + data;
                //将出错的内容写入到错误数据中
                if (state.FileStream == null)
                {
                    if (Writetxt(toKen, data))
                    {
                        try
                        {
                            state.FileStream = File.AppendText(state.Path);
                        }
                        catch
                        {

                        }
                    }
                    else
                    {
                        state.Writes.Add(writeStr);
                    }
                    return;
                }
                else
                {
                    if (state.Writes.Count > 0)
                    {
                        foreach (var item in state.Writes)
                        {
                            //开始写入数据
                            state.FileStream.WriteLine(item);
                        }
                        state.Writes.Clear();
                    }
                }

                //开始写入数据
                state.FileStream.WriteLine(writeStr);
                state.FileStream.Flush();
                state.LastWriteTime = DateTime.Now;
                //如果超过指定时间则
                if (LastCheckTime.AddMinutes(2) < DateTime.Now)
                {
                    CheckWriteTimeOut();
                }
            }
            catch (Exception)
            {
                Delete(key);
            }
        }

        /// <summary>
        /// 写入字符串数据
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        protected bool Writetxt(string tag, string data)
        {
            try
            {
                var path = LogPath(tag);
                using (var fso = File.AppendText(path))
                {
                    fso.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " : " + data);
                    fso.Close();
                }
                return true;
            }
            catch
            {
                return false;

            }
        }

        /// <summary>
        /// 创建目录及文件
        /// </summary>
        /// <param name="tag">标识</param>
        /// <returns></returns>
        protected string LogPath(string tag = null)
        {
            CreatePath();
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            if (tag == null)
            {
                return AppDomain.CurrentDomain.BaseDirectory + @"\" + logHelper.BaseLogPath + @"\" + @"\" + date + ".txt";
            }
            else
            {
                return AppDomain.CurrentDomain.BaseDirectory + @"\" + logHelper.BaseLogPath + @"\" + @"\" + date + tag + ".txt";
            }

        }

        /// <summary>
        /// 获取当前日志运行的基本目录
        /// </summary>
        private string _GetBaseDirectory;
        /// <summary>
        /// 获取当前日志运行的基本目录
        /// </summary>
        public string GetBaseDirectory
        {
            get
            {
                if (string.IsNullOrEmpty(_GetBaseDirectory))
                {
                    //初始化目录 
                    CreatePath();
                }
                return _GetBaseDirectory;
            }
            protected set { _GetBaseDirectory = value; }
        }

        /// <summary>
        /// 创建目录
        /// </summary>
        protected void CreatePath()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + @"\" + logHelper.BaseLogPath + @"\";
            GetBaseDirectory = path;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

    }

}

